/*
 * @Author: malei
 * @Date: 2021-06-16 16:54:39
 * @LastEditors: malei
 * @LastEditTime: 2021-06-16 16:56:20
 */

#include "external_video_capturer.h"
#include "external_video_capturer_module.h"
#include "rtc_base/checks.h"
#include "rtc_base/logging.h"
#include "rtc_base/ref_counted_object.h"


ExternalVideoCapturer::ExternalVideoCapturer() : extc_(nullptr) {}

bool ExternalVideoCapturer::Initialize()
{
    Destroy();

    extc_ = new rtc::RefCountedObject<ExternalVideoCapturerModule>();

    extc_->RegisterCaptureDataCallback(this);

    if (extc_->StartCapture(capability_) != 0)
    {
        Destroy();
        return false;
    }

    RTC_CHECK(extc_->CaptureStarted());

    return true;
}

std::unique_ptr<ExternalVideoCapturer> ExternalVideoCapturer::Create()
{
    auto extCapturer =  std::make_unique<ExternalVideoCapturer>();
    
    if (!extCapturer->Initialize())
        return nullptr;
    
    return std::move(extCapturer);
}

void ExternalVideoCapturer::Destroy()
{
    if (!extc_)
        return;

    extc_->StopCapture();
    extc_->DeRegisterCaptureDataCallback();
    // Release reference to VCM.
    extc_ = nullptr;
}

ExternalVideoCapturer::~ExternalVideoCapturer()
{
    Destroy();
}

void ExternalVideoCapturer::OnFrame(const webrtc::VideoFrame &frame)
{
    VideoCapturer::OnFrame(frame);
}

void ExternalVideoCapturer::OnExternalVideoCaptured(const uint8_t *data, unsigned int len, int width, int height, int64_t ntpTimestamp)
{
    webrtc::VideoCaptureCapability vcb;
    vcb.width = width;
    vcb.height = height;
    vcb.videoType = webrtc::VideoType::kI420;
    extc_->OnExternalVideoCaptured(data, len, vcb, ntpTimestamp);
}
